package com.liuwei.assemble.controller;

import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.liuwei.assemble.common.Result;
import com.liuwei.assemble.vo.GeneratorReqVO;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuwei19
 */
@Slf4j
@RestController
@RequestMapping("tables")
public class TablesController{

    @PostMapping
    public Result getTables(GeneratorReqVO requestVO) throws SQLException {
        DataSourceConfig ds=new DataSourceConfig();
        ds.setDbType(requestVO.getDbType());
        ds.setDriverName(requestVO.getDriverNameFromType());
        ds.setUsername(requestVO.getUsername());
        ds.setPassword(requestVO.getPassword());
        ds.setUrl(requestVO.getConnectionUrl());
        StrategyConfig strategy = null;
        if (requestVO.getSpecifiedTable() != null) {
            List<String> specifiedTableList = new ArrayList<String>();
            for (String table: requestVO.getSpecifiedTable().split(",")) {
                String str = table != null ? table.trim() : null;
                if (StringUtils.isNotEmpty(str)) {
                    specifiedTableList.add(str);
                }
            }

            if (specifiedTableList != null && specifiedTableList.size() > 0) {
                strategy = new StrategyConfig();
                strategy.setInclude(specifiedTableList.toArray(new String[]{}));
            }
        }
        checkDbConnection(requestVO);
        ConfigBuilder config = new ConfigBuilder(null, ds, strategy, null, null);
        List<TableInfo> tableInfos =  config.getTableInfoList();
        return Result.success(tableInfos);
    }

    private void checkDbConnection(GeneratorReqVO requestVO) throws SQLException {
        String url = requestVO.getConnectionUrl();
        //StringHelper.format("jdbc:{}://{}:{}/{}",requestVO.getDbType(),requestVO.getConnectionUrl(),requestVO.getPort(),requestVO.getDatabaseName()) ;
        String user = requestVO.getUsername();
        String password = requestVO.getPassword();
        Connection connection = DriverManager.getConnection(url, user, password);
    }
}
